package j.nawks.wx.api.process.encode.handler;

import j.nawks.wx.api.message.entity.response.RepMessage;
import j.nawks.wx.api.process.encode.EncodeContext;
import j.nawks.wx.api.process.encode.EncodeHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class AbstractEncodeHandler<T extends RepMessage> implements
		EncodeHandler<T> {
	private EncodeHandler<? extends RepMessage> nextHandler;

	public EncodeHandler<? extends RepMessage> getNextHandler() {
		return nextHandler;
	}

	public void setNextHandler(EncodeHandler<? extends RepMessage> nextHandler) {
		this.nextHandler = nextHandler;
	}

	public void nextProcess(T repMessage, EncodeContext cxt) {
		EncodeHandler<? extends RepMessage> handler = getNextHandler();
		Method method = null;
		while (handler != null) {
			try {
				method = handler.getClass().getDeclaredMethod("process",
						new Class[] { RepMessage.class, EncodeContext.class });
				if (method.getParameterTypes()[0].isInstance(repMessage)) {
					break;
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		if (handler != null) {
			try {
				method.invoke(handler, repMessage,cxt);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
